package com.foogui.primary.communication;

import com.foogui.common.vo.Message;

import java.util.concurrent.Exchanger;

public class ExchangerDemo {
    public static void main(String[] args) throws InterruptedException {
        Exchanger<Message> exchanger = new Exchanger<>();
        new Thread(() -> {
            try {
                // 生成数据
                Message message = new Message("标题A","内容A");
                Message msg = exchanger.exchange(message);
                System.out.println("这是线程A，得到了另一个线程的数据："
                        + msg.getContext());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        System.out.println("这个时候线程A是阻塞的，在等待线程B的数据");
        Thread.sleep(1000);

        new Thread(() -> {
            try {
                // 生成数据
                Message message = new Message("标题B","内容B");
                Message msg = exchanger.exchange(message);
                System.out.println("这是线程B，得到了另一个线程的数据："
                        + msg.getContext());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

    }
}
